/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Models.DAOs;

/**
 *
 * @author 0905
 */

import DBConnection.ConnectionFactory;
import Models.Order;
import Models.OrderInfo;
import Models.Products;
import com.mysql.jdbc.CallableStatement;
import java.lang.Exception;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class Order_DAO {
    
    
    public boolean addOrder(OrderInfo order){
        try{
            
            /* Link transaction to a customer */
            ConnectionFactory myFactory = ConnectionFactory.getFactory();
            Connection conn = myFactory.getConnection();
            int i = 1; int j = 1;
            PreparedStatement pstmtOrder = conn.prepareStatement("INSERT INTO order(customerID, orderDate) VALUES (?,?)");

            
            pstmtOrder.setInt(i, order.getCustomerID());
            pstmtOrder.setString(i, order.getOrderDate());
            pstmtOrder.executeUpdate();
            
            
            /* Get orderID of transaction */
            PreparedStatement pstmtLastID = conn.prepareStatement("LAST_INSERT_ID");
            ResultSet rs = pstmtLastID.executeQuery();
            if(rs.next())
            {
                int lastID = rs.getInt(1);
                order.setOrderID(lastID);
            }
            
            
            /* Add order information to transaction with multiple orders*/
            int ProductIDlist = order.getProductIDlist().size(); // get number of orders in transaction
            
            
            PreparedStatement pstmtOrderInfo = conn.prepareStatement("INSERT INTO orderinfo (orderID, productID, quantity) VALUES(?,?,?)");
  
            for( int k = 0; k < ProductIDlist; k++ ) // for each order in transaction, insert into orderInfo
            {
                int productID = order.getProductIDlist().get(k);
                int quantity = order.getQuantityList().get(k);
                
                pstmtOrderInfo.setInt(j, order.getOrderID());
                pstmtOrderInfo.setInt(j, productID);
                pstmtOrderInfo.setInt(j,quantity);
                pstmtOrderInfo.executeUpdate();
                
                j = 1;
            }
           
            
            return true;
        }
        catch(SQLException e){
            e.printStackTrace();
            return false;
        }
    }
    
    
}
